﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Linq;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dimok.Exceptions;
using Data.LINQ;

public partial class Controls_Upload_UploadBatch : System.Web.UI.Page {
	protected void Page_Load(object sender, EventArgs e) {
		if (Request.Files.Count > 0) {
			byte[] file = new byte[Request.Files[0].InputStream.Length];
			Request.Files[0].InputStream.Read(file, 0, (int)Request.Files[0].InputStream.Length);
			string fileName = Dimok.FileManager.GetFileFromBytes(file, @"C:\Data\" + (UInt64)Environment.TickCount + ".xls");
			string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName +
				";Extended Properties=\"EXCEL 8.0;HDR=YES\"";
			var mb = new MotoBank();
			try {
				var uploadBatchID = Dimok.Common.ParseInt(Request["hdnUploadInfoID"]);
				if (uploadBatchID == 0) throw new Exception("hdnUploadInfoID field is not found in request.");
				var interestTypeID = Lib.MakeInt(Request["hdnInterestTypeID"]);
				var paymentsPerYear = Lib.MakeInt(Request["hdnPaymentsPerYear"]);
				using (OleDbConnection conn = new OleDbConnection(connectionString)) {
					using (OleDbCommand comm = new OleDbCommand("SELECT * FROM [Sheet1$]", conn)) {
						OleDbDataAdapter da = new OleDbDataAdapter(comm);
						DataTable dtIn = new DataTable();
						da.Fill(dtIn);
						var uploadInfo = mb.t_UploadInfos.SingleOrDefault(r => r.ID == uploadBatchID);
						if (uploadInfo == null) throw new Exception("No Upload Info is found with ID:" + uploadBatchID);
						uploadInfo.t_Uploads.AddRange(dtIn.ToIEnumerable<t_Upload>());
						if( interestTypeID +paymentsPerYear > 0 )
							foreach (var u in uploadInfo.t_Uploads) {
								if (paymentsPerYear > 0) u.Pmt_Freq = paymentsPerYear + "";
								if (interestTypeID > 0) u.InterestTypeID = (byte)interestTypeID;
							}
						//mb.t_UploadInfos.InsertOnSubmit(uploadInfo);
						mb.SubmitChanges(ConflictMode.ContinueOnConflict);
					}
				}
				message.InnerHtml = "Done!";
			} catch (Exception exc) {
				exc.Data.Add("ConnectionString", connectionString);
				ASPException.Publish(exc);
				message.InnerHtml = this.Server.UrlPathEncode(ASPException.GetMessages(exc));
			} finally {
				File.Delete(fileName);
			}
		}

	}
}
